#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

#define NUM 32
char cmd_line[NUM];
char* argv[NUM];
const char* SEP = " ";

int main()
{
    while(1)
    {
        printf("[bobo]& ");
        fflush(stdout);
        //获取命令行字符串
        memset(cmd_line,'\0',sizeof(cmd_line));
        if(fgets(cmd_line,sizeof(cmd_line),stdin) == NULL)
        {
            continue;
        }
        cmd_line[strlen(cmd_line)-1] = '\0';
        //打散命令行字符串
        argv[0] = strtok(cmd_line,SEP);
        int i = 1;
        if(strcmp(argv[0],"ls") == 0) argv[i++] = "--color=auto";//添加颜色
        while(argv[i++] = strtok(NULL,SEP));
        if(strcmp(argv[0],"cd") == 0)//父进程执行的命令叫做内置命令，此时不创建子进程，所以用continue
        {
            if(argv[1] != NULL)
            {
                chdir(argv[1]);
            }
            continue;
        }
        //创建子进程
        pid_t id = fork();
        if(id == 0)
        {
            //child
            execvp(argv[0],argv);
            exit(1);
        }
        else 
        {
            int status;
            waitpid(-1,&status,0);
        }
    }
    return 0;
}
